package com.lzb.compressmaster.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.lzb.compressmaster.BaseAc;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.adapter.DocumentsAdapter;
import com.lzb.compressmaster.adapter.RecentFileAdapter;
import com.lzb.compressmaster.basic.media.AudioBean;
import com.lzb.compressmaster.basic.media.MediaInfo;
import com.lzb.compressmaster.basic.media.MediaLoader;
import com.lzb.compressmaster.bean.RecentFileBean;
import com.lzb.compressmaster.databinding.ActivityRecentFileBinding;
import com.lzb.compressmaster.dialog.AudioPreviewDialog;
import com.lzb.compressmaster.utils.MimeUtils;
import com.lzb.compressmaster.utils.RecentFilesManager;
import com.lzb.compressmaster.utils.RxUtil;

import java.io.File;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class RecentFileActivity extends BaseAc<ActivityRecentFileBinding> implements OnItemChildClickListener, OnItemClickListener {

    private RecentFileAdapter recentFileAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_recent_file;
    }

    @Override
    protected void initView() {
        mDataBinding.ivRecentFileBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        recentFileAdapter = new RecentFileAdapter();
        mDataBinding.rvFileList.setAdapter(recentFileAdapter);
//        recentFileAdapter.addChildClickViewIds(R.id.ivRecentFileItemShow);
        recentFileAdapter.setOnItemChildClickListener(this);
        recentFileAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof RecentFileAdapter) {
            if (recentFileAdapter.getItem(position).isSelected()) {
                recentFileAdapter.getItem(position).setSelected(false);
            } else {
                recentFileAdapter.getItem(position).setSelected(true);
            }
            recentFileAdapter.notifyItemChanged(position);
        } else if (adapter instanceof DocumentsAdapter) {
            DocumentsAdapter documentsAdapter = (DocumentsAdapter) adapter;
            MediaInfo item = documentsAdapter.getItem(position);
            String path = item.getPath();
            if (FileUtils.isDir(path)) {
                Intent intent = new Intent(this, PhoneStorageActivity.class);
                intent.putExtra(Content.path, path);
                startActivity(intent);
            } else if (MimeUtils.isImgMimeType(path)) {
                ImageViewer.load(path)//要加载的图片数据，单张或多张
                        .imageLoader(new GlideImageLoader())// 图片加载器，目前内置的有CoilImageLoader、GlideImageLoader和PicassoImageLoader，也可以自己实现
                        .selection(position)//当前选中位置，默认：0
                        .showIndicator(true)//是否显示指示器，默认不显示
                        .theme(com.king.image.imageviewer.R.style.ImageViewerTheme)//设置主题风格，默认：R.style.ImageViewerTheme
                        .orientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//设置屏幕方向,默认：ActivityInfo.SCREEN_ORIENTATION_BEHIND
                        .start(this);//activity or fragment, 跳转时的共享元素视图
            } else if (MimeUtils.isVideoMimeType(path)) {
                VideoPreviewActivity.sVideoPath = path;
                startActivity(VideoPreviewActivity.class);
            } else if (MimeUtils.isAudioMimeType(path)) {
                showAudioPreviewDialog(path);
            } else {
                gotoPreview(UriUtils.file2Uri(new File(path)));
            }
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivRecentFileItemShow) {

        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<RecentFileBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<RecentFileBean>> emitter) {
                List<RecentFileBean> recentFileBeans = new RecentFilesManager(mContext).getRecentFiles(100);
                emitter.onNext(recentFileBeans);
            }

            @Override
            public void accept(List<RecentFileBean> recentFileBeanList) {
                if (recentFileBeanList != null && recentFileBeanList.size() != 0) {
                    recentFileAdapter.setList(recentFileBeanList);
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.flFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.flFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void showAudioPreviewDialog(String path) {
        AudioPreviewDialog audioPreviewDialog = new AudioPreviewDialog(mContext);
        audioPreviewDialog.setAudioPath(path);
        audioPreviewDialog.show();
    }

    //跳转到预览应用
    private void gotoPreview(Uri selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(selUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            startActivity(intent);
        } else {
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }

}